package cn.chinaunicom.mini.program.dingtalk.openapi.service;

import java.util.Objects;

import com.alibaba.fastjson2.JSON;
import com.dingtalk.api.request.OapiRoleSimplelistRequest;
import com.dingtalk.api.response.OapiRoleSimplelistResponse;
import org.springframework.stereotype.Component;

import com.dingtalk.api.request.OapiRoleGetroleRequest;
import com.dingtalk.api.request.OapiRoleListRequest;
import com.dingtalk.api.response.OapiRoleGetroleResponse;
import com.dingtalk.api.response.OapiRoleListResponse;
import com.taobao.api.ApiException;

import cn.chinaunicom.mini.program.dingtalk.openapi.client.IDingTalkClient;
import lombok.extern.slf4j.Slf4j;

/**
 * @ProjectName: dingtalk-adapter
 * @Package: cn.chinaunicom.mini.program.dingtalk.openapi.service
 * @ClassName: DingTalkRoleAPI
 * @Description: 钉钉角色管理API
 * @Author: wangjc
 * @CreateDate: 2024/6/12
 * @UpdateUser: wangjc
 * @UpdateDate: 2024/6/12
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
@Slf4j
@Component
public class DingTalkRoleAPI {

	/**
	 * 查询角色列表的接口调用方法。
	 *
	 * @param req 查询角色列表的请求参数对象。
	 * @return 返回角色列表的响应数据。
	 */
	public OapiRoleListResponse.PageVo listRole(OapiRoleListRequest req, String accessToken) throws ApiException{
		// 检查请求参数中是否设置了分页信息，如果没有，则默认设置为每页20条，从第0条开始
		if (Objects.isNull(req.getSize()) && Objects.isNull(req.getOffset())) {
			req.setSize(20L);
			req.setOffset(0L);
		}
		// 执行接口调用，获取角色列表
		OapiRoleListResponse rsp = IDingTalkClient.execute("https://oapi.dingtalk.com/topapi/role/list", req,
				accessToken);
		// 返回角色列表的响应数据
		log.debug("钉钉开放平台接口响应体：{}", JSON.toJSONString(rsp.getBody()));
		return rsp.getResult();
	}

	/**
	 * 查询单个角色信息的接口调用方法。
	 *
	 * @param req 查询单个角色信息的请求参数对象。
	 * @return 返回角色信息的响应数据。
	 */
	public OapiRoleGetroleResponse.OpenRole getRoleInfo(OapiRoleGetroleRequest req, String accessToken) throws ApiException {
		// 执行接口调用，获取单个角色信息
		OapiRoleGetroleResponse rsp = IDingTalkClient.execute("https://oapi.dingtalk.com/topapi/role/getrole", req,
				accessToken);
		// 返回角色信息的响应数据
		log.debug("钉钉开放平台接口响应体：{}", JSON.toJSONString(rsp.getBody()));
		return rsp.getRole();
	}

	public OapiRoleSimplelistResponse listUserByRoleId(OapiRoleSimplelistRequest req, String accessToken) throws ApiException {
		if (Objects.isNull(req.getSize()) && Objects.isNull(req.getOffset())) {
			req.setSize(20L);
			req.setOffset(0L);
		}
		OapiRoleSimplelistResponse rsp = IDingTalkClient.execute("https://oapi.dingtalk.com/topapi/role/simplelist", req, accessToken);
		log.debug("钉钉开放平台接口响应体：{}", JSON.toJSONString(rsp.getBody()));
		return rsp;
	}
}
